
/**
  ******************************************************************************
  * Copyright 2021 The grapilot Authors. All Rights Reserved.
  * 
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  * 
  * http://www.apache.org/licenses/LICENSE-2.0
  * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  * 
  * @file       fms_radio.c
  * @author     baiyang
  * @date       2021-8-23
  ******************************************************************************
  */

/*----------------------------------include-----------------------------------*/
#include "fms.h"
/*-----------------------------------macro------------------------------------*/
#define FS_COUNTER 3        // radio failsafe kicks in after 3 consecutive throttle values below failsafe_throttle_value
#define THROTTLE_ZERO_DEBOUNCE_TIME_MS 400
/*----------------------------------typedef-----------------------------------*/

/*---------------------------------prototype----------------------------------*/
void fms_set_throttle_and_failsafe(uint16_t throttle_pwm);
void fms_set_throttle_zero_flag(int16_t throttle_control);

/*----------------------------------variable----------------------------------*/

/*-------------------------------------os-------------------------------------*/

/*----------------------------------function----------------------------------*/
// Function that will read the radio data, limit servos and trigger a failsafe
// ----------------------------------------------------------------------------

void fms_default_dead_zones()
{
    RC_set_default_dead_zone(fms.channel_roll, 20);
    RC_set_default_dead_zone(fms.channel_pitch, 20);

    RC_set_default_dead_zone(fms.channel_throttle, 30);
    RC_set_default_dead_zone(fms.channel_yaw, 20);
    RC_set_default_dead_zone(&(fms.channels.channel[5]), 0);
}

void fms_init_rc_in()
{
    RC_register_callback(fms_set_mode_rc);

    RCs_init(&(fms.channels));

    fms.channel_roll     = &(fms.channels.channel[PARAM_GET_INT8(RC,RCMAP_ROLL)-1]);
    fms.channel_pitch    = &(fms.channels.channel[PARAM_GET_INT8(RC,RCMAP_PITCH)-1]);
    fms.channel_throttle = &(fms.channels.channel[PARAM_GET_INT8(RC,RCMAP_THROTTLE)-1]);
    fms.channel_yaw      = &(fms.channels.channel[PARAM_GET_INT8(RC,RCMAP_YAW)-1]);

    // set rc channel ranges
    RC_set_angle(fms.channel_roll, ROLL_PITCH_YAW_INPUT_MAX);
    RC_set_angle(fms.channel_pitch, ROLL_PITCH_YAW_INPUT_MAX);
    RC_set_angle(fms.channel_yaw, ROLL_PITCH_YAW_INPUT_MAX);
    RC_set_range(fms.channel_throttle, 1000);

    // set default dead zones
    fms_default_dead_zones();

    lpf_set_cutoff1(&(fms.rc_throttle_control_in_filter), 1.0f);

    // initialise throttle_zero flag
    fms.ap.throttle_zero = true;
}

// enable_motor_output() - enable and output lowest possible value to motors
void fms_enable_motor_output()
{
    // enable output to motors
    MotorsMat_output_min((MotorsMat_HandleTypeDef *)fms.motors);
}

void fms_read_radio()
{
    const uint32_t tnow_ms = time_millis();

    if (RCs_read_input(&(fms.channels))) {
        fms.ap.new_radio_frame = true;

        fms_set_throttle_and_failsafe(fms.channel_throttle->radio_in);
        fms_set_throttle_zero_flag(fms.channel_throttle->control_in);

        // RC receiver must be attached if we've just got input
        fms.ap.rc_receiver_present = true;

        // pass pilot input through to motors (used to allow wiggling servos while disarmed on heli, single, coax copters)
        //radio_passthrough_to_motors();

        const float dt = (tnow_ms - fms.last_radio_update_ms)*1.0e-3f;
        lpf_apply2(&(fms.rc_throttle_control_in_filter), fms.channel_throttle->control_in, dt);
        fms.last_radio_update_ms = tnow_ms;
        return;
    }

    // No radio input this time
    if (fms.failsafe.radio) {
        // already in failsafe!
        return;
    }

    const uint32_t elapsed = tnow_ms - fms.last_radio_update_ms;
    // turn on throttle failsafe if no update from the RC Radio for 500ms or 2000ms if we are using RC_OVERRIDE
    const uint32_t timeout = RCs_has_active_overrides(&(fms.channels)) ? FS_RADIO_RC_OVERRIDE_TIMEOUT_MS : FS_RADIO_TIMEOUT_MS;
    if (elapsed < timeout) {
        // not timed out yet
        return;
    }
    
    if (!fms.g.failsafe_throttle) {
        // throttle failsafe not enabled
        return;
    }

    if (!fms.ap.rc_receiver_present && !fms.motors->_armed) {
        // we only failsafe if we are armed OR we have ever seen an RC receiver
        return;
    }

    // Nobody ever talks to us.  Log an error and enter failsafe.
    //AP::logger().Write_Error(LogErrorSubsystem::RADIO, LogErrorCode::RADIO_LATE_FRAME);
    //set_failsafe_radio(true);
}

void fms_set_throttle_and_failsafe(uint16_t throttle_pwm)
{
    // if failsafe not enabled pass through throttle and exit
    if(fms.g.failsafe_throttle == FS_THR_DISABLED) {
        return;
    }

    //check for low throttle value
    if (throttle_pwm < (uint16_t)fms.g.failsafe_throttle_value) {

        // if we are already in failsafe or motors not armed pass through throttle and exit
        if (fms.failsafe.radio || !(fms.ap.rc_receiver_present || fms.motors->_armed)) {
            return;
        }

        // check for 3 low throttle values
        // Note: we do not pass through the low throttle until 3 low throttle values are received
        fms.failsafe.radio_counter++;
        if( fms.failsafe.radio_counter >= FS_COUNTER ) {
            fms.failsafe.radio_counter = FS_COUNTER;  // check to ensure we don't overflow the counter
            //set_failsafe_radio(true);
        }
    }else{
        // we have a good throttle so reduce failsafe counter
        fms.failsafe.radio_counter--;
        if( fms.failsafe.radio_counter <= 0 ) {
            fms.failsafe.radio_counter = 0;   // check to ensure we don't underflow the counter

            // disengage failsafe after three (nearly) consecutive valid throttle values
            if (fms.failsafe.radio) {
                //set_failsafe_radio(false);
            }
        }
        // pass through throttle
    }
}

// set_throttle_zero_flag - set throttle_zero flag from debounced throttle control
// throttle_zero is used to determine if the pilot intends to shut down the motors
// Basically, this signals when we are not flying.  We are either on the ground
// or the pilot has shut down the copter in the air and it is free-falling
void fms_set_throttle_zero_flag(int16_t throttle_control)
{
    static uint32_t last_nonzero_throttle_ms = 0;
    uint32_t tnow_ms = time_millis();

    // if not using throttle interlock and non-zero throttle and not E-stopped,
    // or using motor interlock and it's enabled, then motors are running, 
    // and we are flying. Immediately set as non-zero
    if ((!fms.ap.using_interlock && (throttle_control > 0)) ||
        (fms.ap.using_interlock && fms.motors->_interlock) ||
        fms.ap.armed_with_switch) {
        last_nonzero_throttle_ms = tnow_ms;
        fms.ap.throttle_zero = false;
    } else if (tnow_ms - last_nonzero_throttle_ms > THROTTLE_ZERO_DEBOUNCE_TIME_MS) {
        fms.ap.throttle_zero = true;
    }
}
/*------------------------------------test------------------------------------*/


